/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers;

import app.Const;
import com.alibaba.fastjson.JSON;
import com.github.sog.config.JFinalApp;
import com.github.sog.config.StringPool;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.kit.encry.EncodeKit;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-09 16:50
 * @since JDK 1.6
 */
public class FileController extends BasicController {

    public static final  Rename SUFFIX_DPI = new Rename() {
        @Override
        public String apply(String fileName, ThumbnailParameter param) {
            final Dimension size = param.getSize();
            return appendSuffix(fileName, StringPool.DASH + (int) size.getWidth() + "x" + (int) size.getHeight());
        }
    };
    private static final Logger logger     = LoggerFactory.getLogger(FileController.class);
    public static final String uploadroot = "/attachment/";
    private static String root;

    /**
     * The index route.
     */
    public void index() {

        renderError(404);
    }

    /**
     * 单个或多个文件上传
     */
    public void up() {
        String savefilename;
        StringBuilder files = new StringBuilder();
        List<UploadFile> upfilelist = this.getFiles();
        if (upfilelist != null && !upfilelist.isEmpty()) {
            if (root == null)
                root = this.getRequest().getContextPath();

            String dpi = getPara("dpi");

            String realPath = PathKit.getWebRootPath();
            int fsize = upfilelist.size();
            int i = 1;
            for (UploadFile upfile : upfilelist) {
                File file = upfile.getFile();
                String filedataFileName = upfile.getOriginalFileName();
                String extension = Files.getFileExtension(filedataFileName);
                if (
                        StringUtils.equalsIgnoreCase(extension, "jpg")
                                || StringUtils.equalsIgnoreCase(extension, "png")
                                || StringUtils.equalsIgnoreCase(extension, "jpeg")
                                || StringUtils.equalsIgnoreCase(extension, "gif")
                                || StringUtils.equalsIgnoreCase(extension, "bmp")
                        ) {
                    savefilename = uploadroot + EncodeKit.toUUID() + StringPool.DOT + extension;
                    if (file != null) {
                        File saveNewFile = new File(realPath, savefilename);
                        try {
                            Files.createParentDirs(saveNewFile);
                        } catch (IOException e) {
                            logger.error("upload file create parent dir is error!", e);
                            this.renderText(JSON.toJSONString(AjaxMessage.error("未上传文件")));
                            return;
                        }
                        if (file.renameTo(saveNewFile)) {
                            files.append(savefilename);
                            if (i < fsize) {
                                files.append(StringPool.COMMA);
                            }
                            try {
                                Thumbnails.of(saveNewFile).size(200, 120).outputFormat(extension).toFiles(Rename.SUFFIX_DOT_THUMBNAIL);

                                if (!Strings.isNullOrEmpty(dpi)) {

                                    if (StringUtils.equals(dpi, "logo")) {
                                        //logo
                                        Thumbnails.of(saveNewFile).size(58, 58).keepAspectRatio(false)
                                                .outputFormat(extension).toFiles(SUFFIX_DPI);
                                    } else if (StringUtils.equals(dpi, "env")) {
                                        // enviroment
                                        Thumbnails.of(saveNewFile).size(125, 92).keepAspectRatio(false)
                                                .outputFormat(extension).toFiles(SUFFIX_DPI);
                                        Thumbnails.of(saveNewFile).size(136, 106).keepAspectRatio(false)
                                                .outputFormat(extension).toFiles(SUFFIX_DPI);
                                    } else if (StringUtils.equals(dpi, "bacvtity")) {
                                        // brand activity logo
                                        Thumbnails.of(saveNewFile).size(54, 54).keepAspectRatio(false)
                                                .outputFormat(extension).toFiles(SUFFIX_DPI);
                                    }
                                }

                            } catch (IOException e) {
                                logger.warn("create thumbnail image file is error!", e);
                            }
                        }
                    }
                    i++;
                } else {
                    this.renderText(JSON.toJSONString(AjaxMessage.error("请上传图片文件!")));
                    return;
                }
            }
        } else {
            this.renderText(JSON.toJSONString(AjaxMessage.error("未上传文件")));
            return;
        }
        this.renderText(JSON.toJSONString(AjaxMessage.ok(StringUtils.EMPTY, files.toString())));
    }


    public void editor() {
        String savefilename;
        StringBuilder files = new StringBuilder();
        List<UploadFile> upfilelist = this.getFiles();
        Map<String, Object> rst = Maps.newHashMap();
        if (upfilelist != null && !upfilelist.isEmpty()) {
            if (root == null)
                root = this.getRequest().getContextPath();
            String realPath = PathKit.getWebRootPath();
            UploadFile upfile = upfilelist.get(0);
            File file = upfile.getFile();
            String filedataFileName = upfile.getOriginalFileName();
            String extension = Files.getFileExtension(filedataFileName);
            if (StringUtils.equalsIgnoreCase(extension, "jpg")
                    || StringUtils.equalsIgnoreCase(extension, "png")
                    || StringUtils.equalsIgnoreCase(extension, "jpeg")
                    || StringUtils.equalsIgnoreCase(extension, "gif")
                    || StringUtils.equalsIgnoreCase(extension, "bmp")
                    ) {
                savefilename = uploadroot + EncodeKit.toUUID() + "." + extension;
                if (file != null) {
                    File saveNewFile = new File(realPath, savefilename);
                    try {
                        Files.createParentDirs(saveNewFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (file.renameTo(saveNewFile)) {
                        files.append(savefilename);
                    }
                }
            } else {
                rst.put("error", 1);
                rst.put("message", "请上传图片文件!");

                this.renderText(JSON.toJSONString(rst));
                return;
            }
        } else {
            rst.put("error", 1);
            rst.put("message", "未上传文件!");
            this.renderText(JSON.toJSONString(rst));
            return;
        }
        rst.put("error", 0);
        rst.put("url", JFinalApp.domain + files.toString());
        this.renderText(JSON.toJSONString(rst));
    }


    public void remove() {
        if (root == null)
            root = this.getRequest().getContextPath();

        String path = getPara(Const.DATA_PARAM);


        String realPath = PathKit.getWebRootPath();
        String fileName = Files.getNameWithoutExtension(path);
        String extension = Files.getFileExtension(path);

        final File file = new File(realPath, path);
        try {
            if (file.exists()) {

                FileUtils.deleteQuietly(file);

                delete_thumbnails(realPath, fileName, new String[]{".thumbnail.", "-58x58.", "-54x54.", "-136x106.", "-125x92."}, extension);

            } else {
                logger.warn("the file {} cannot found!", path);
            }
            renderSuccess();
        } catch (Exception e) {
            logger.error("delete picute file is error!", e);
            renderError("删除文件失败，请联系管理员!");
        }

    }

    private void delete_thumbnails(String realPath, String fileName, String[] thumbnails, String extension) {
        for (String thumbnail : thumbnails) {
            String thumbnail_path = uploadroot + fileName + thumbnail + extension;
            final File thumbnail_file = new File(realPath, thumbnail_path);
            if (thumbnail_file.exists()) {
                FileUtils.deleteQuietly(thumbnail_file);
            }
        }

    }
}